<? 
define ('DATA_PATH', '/var/www/temp/data');
define ('QUEUE_PATH', '/var/www/shadow.net/client');

require("queue.progress.php");   
require("../webnews/nntp.php");   
function Page_Load()
{
    global $argv;
    $messageKey = $argv[1];   

    $messageDoc = QUEUE_DATA . "/{$messageKey}.pend";
    if (!file_exists($messageDoc)) return;
    echo "\n{$messageDoc}\n";
    $message = file_get_contents ($messageDoc);
    unlink ($messageDoc);
    echo $message;
    echo "\n\n";

    $unpacked   = simplexml_load_string($message);  
    $groupName  = "{$unpacked->groupname}"; 
    $articleKey = "{$unpacked->article}"; 
    $saveAs     = "{$unpacked->savedir}"; 
    $pageFilter = "{$unpacked->filter}"; 
    $pageSearch = "{$unpacked->search}"; 
    $pageNumber = "{$unpacked->pagenumber}"; 
    $pageSaved  = "{$unpacked->saved}"; 



    $server = new Application_Model_NewsServer ($pageFilter, $pageSearch, $saveAs);
    if (strlen($pageNumber) > 0) echo $server->GetPage($groupName, $pageNumber, $messageKey, $pageSaved);
    else if (strpos($articleKey, '/')!==false) echo $server->GetArticles($groupName, explode('/', $articleKey), $messageKey);
    else {
        echo "$groupName, $articleKey, $messageKey\n\n"; 
        echo $server->GetArticle($groupName, $articleKey, $messageKey);
        echo "\n\n";
    }
    SetProgress($messageKey, 1, 1, 'COMPLETE', ""); 
} 

Page_Load();



 
class Application_Model_NewsServer
{

    public $Id;
    public $Yenc;
    public $Encoding = NULL;
    public $GroupName;
    public $NNTP;
    public $Filter = NULL;
    public $Search = NULL;
    public $KeepAlive = NULL;
    public $SaveTo = NULL;
    public $groups;

    function __construct($filter='', $search='', $saveto='')
    {
        $info = array ('server'   => "news.usenet.net",
                        'username' => 'info@cyber8.net',
                        'password' => 'Password');
        $Server     = $info['server'];
        $Username   = $info['username'];
        $Password   = $info['password'];
        $Db         = array(); 
        $this->NNTP = new NNTP($Server, trim($Username), trim($Password));   
        $this->Filter = $filter;
        $this->Search = $search;
        $this->SaveTo = $saveto;
    }


    function GetPage($groupName, $pageNumber, $messageKey, $savedPages="") 
    {

        if (strlen($savedPages) > 0) {
 
            $DATA_URI = DATA_PATH . "/search/{$groupName}/{$savedPages}.xml"; 
        }
        else $DATA_URI = DATA_PATH . "/index/{$groupName}.xml";
        $articleList = simplexml_load_file($DATA_URI);
        $this->articlesets = array();

        $query = "//list/article";
        if ($this->Filter && strlen ($this->Filter) > 0) $query .= "[type='{$this->Filter}']";
        if ($this->Search && strlen ($this->Search) > 0) $query .= "[contains(subject, '{$this->Search}')]"; 

        $result = $articleList->xpath($query);  
        for($x=0;$x<sizeof($result);$x++)
        { 
            $this->articlesets[] = $result[$x];
        }
        echo "\n\n---{$pageNumber}---\n\n";
        SetProgress($messageKey, 1, 0, 'IN PROGRESS', "Beginning download...") ;
        $startIndex = ($pageNumber - 1) * 8;  
        $this->articlesets = array_slice ($this->articlesets, $startIndex, 8);
        $articleCount = sizeof($this->articlesets);

        $this->GroupName = $groupName;
        $this->KeepAlive = true;
        $this->Connect2Group();
        for($x=0;$x<$articleCount;$x++)
        { 
            if ($this->articlesets[$x]->type != 'picture') continue;
            $articleSet = $this->articlesets[$x];
            $articleKey = "{$articleSet->id}";
            echo "{$x}. Downloading {$articleSet->subject}...\n";
            SetProgress($messageKey, $articleCount, $x + 1, 'IN PROGRESS', "Downloading {$articleSet->subject}...") ;
            echo $this->GetArticle($groupName, $articleKey, $messageKey) ;
            echo "\n\n"; 
        } 
        $this->Disconnect();
    }

    function GetArticles($groupName, $articleKeys, $messageKey) 
    { 
        $DATA_URI = DATA_PATH . "/index/{$groupName}.xml"; 
        $articleList = !file_exists($DATA_URI) ? NULL : simplexml_load_file($DATA_URI);
        $diffGroups = false;
       
        for($x=0;$x<sizeof($articleKeys);$x++) $diffGroups = $diffGroups || strpos($articleKeys[$x], ':') !==false;
        if (strlen($groupName) > 0) {

            $this->GroupName = $groupName;
            $this->KeepAlive = true;
            $this->Connect2Group();

        }
        for($x=0;$x<sizeof($articleKeys);$x++)
        {  
            $subject = "article {$x}";
            if ($articleList) {
                $result = $articleList->xpath(sprintf("//article[id='%s']", $articleKeys[$x]));  
                if ($result) {
                     $subject = $result[0]->subject;
                }
            }
            SetProgress($messageKey, sizeof($articleKeys), $x + 1, 'IN PROGRESS', "Downloading {$subject}...") ;
            echo $this->GetArticle($groupName, $articleKeys[$x], $messageKey) ;
            echo "\n\n"; 
        } 
        
        if (strlen($groupName) > 0) $this->Disconnect();

    }

    function MakeDirectory($path) 
    { 
        mkdir ($path);
        passthru ("chmod -R 777 {$path}");
    }

    function GetArticle($groupName, $articleKey, $messageKey) 
    { 
        $this->GroupName  = $groupName;
        if (strpos($articleKey, ':')!==false) {
            $temp = explode (':', $articleKey); 
            $this->GroupName = $temp[0];
            $articleKey = $temp[1];
        }
        $base64Name       = base64_encode ($articleKey);
        $assetFolder      = DATA_PATH . "/asset";
        $groupFolder      = "{$assetFolder}/{$this->GroupName}";
        $picturePath      = "{$groupFolder}/{$base64Name}";
        $pictureEncode    = ""; 
        if (file_exists($picturePath)) return $picturePath; 
        if (!is_dir ($assetFolder)) $this->MakeDirectory ($assetFolder);
        if (!is_dir ($groupFolder)) $this->MakeDirectory ($groupFolder);


        $downloadedArticles = $this->DownloadArticles($articleKey, $this->GroupName);
        
        $body  = array();        
        for ($x=0;$x < sizeof($downloadedArticles); $x++)
        { 
	    $body[] = trim($downloadedArticles[$x]['body']);
        } 

        if (strlen($this->SaveTo)>0) {
            $picturePath = "{$this->SaveTo}/{$articleKey}.news";
            $data = implode ("\n", $body);
            file_put_contents($picturePath, $data); 
            return $picturePath;
        }

        if ($this->Yenc)
        {  
	    $enc  = new yenc();                                                                                                                                                                         
	    $data = $enc->decode($body);    
            file_put_contents($picturePath, $data);
	    return $this->Validate($picturePath); 
        }

        if ($this->Encoding) $pictureEncode = $this->Encoding; 
	if (strlen($pictureEncode) == 0) $pictureEncode = 'uuencode';		
		
        $messageContent = array ('header' => array('content-transfer-encoding' => $pictureEncode), 
                                  'body'   => implode("\n", $body));   

        $messageBody = $messageContent['body'];
        if (preg_match("/^begin\s+\d{3}\s+(.*)$/im", $messageBody, $header))
	{
            $messageBody = str_replace($header[0], "", $messageBody);   
            $messageContent['body'] = trim($messageBody);
	}   
	    
        $data = decode_message_content($messageContent);
        file_put_contents($picturePath, $data); 
	return $this->Validate($picturePath);  
    }

    
    function Validate ($filename)
    {   
	echo "Testing image {$filename}...\n";
	$im = $this->ImageCreate ($filename); 
	if ($im)
	{
	    imagedestroy($im);
	    echo filesize ($filename) . " bytes saved\n";
            return $filename;
	} 
	    
	echo "Imaging test failed!! Deleting...\n";
	unlink ($filename); 
	return NULL;     
    }

    
    function ImageCreate($filename)
    {
        $im = @imagecreatefromjpeg ($filename);
        if (!$im) $im = @imagecreatefromgif ($filename);
        if (!$im) $im = @imagecreatefrompng ($filename);
        return $im;
    }
    
    function Connect2Group ()
    {      
        if (!$this->NNTP->connect())                                                
        {                                                
            echo "Unable to connect!";                                             
            return false;                                               
        }  
        
	if ( ! ( $gi=$this->NNTP->join_group(trim($this->GroupName)) ) )                    
	{
	    echo "Unable to join group [$this->GroupName]";  
	    $this->Disconnect();
	    return false;
	}   
        return $gi;
    }
    
    function Disconnect()
    {
        $this->NNTP->quit();
    } 

    function DownloadArticles ($id = '', $groupname = '')
    {       
        if (strlen($id) > 0) $this->Id = $id;
        $this->GroupName =  $groupname;
        $messages = array();
        $ids      = explode ('-', $this->Id);    
        if (!$this->KeepAlive) $this->Connect2Group();
        if (sizeof($ids) > 12) return;

	for ($i=0;$i<sizeof($ids);$i++)
	{
            $key = $ids[$i];
	    echo "Downloading article [$key]...\n";  
            $message = $this->NNTP->get_article($key);    
            $messages[] = $message;
	} 
        
        if (!$this->KeepAlive) $this->Disconnect();
        
        return $this->Assemble($messages);
    }


    function Assemble ($messages)
    {
        $content = array();        
		for ($i=0;$i<sizeof($messages);$i++)     
		{             
		    $MIME_Message = $messages[$i];
		    if (!$MIME_Message)
		    {
		        continue;
		    }
            $header = $MIME_Message->get_main_header();                                               
            $parts  = $MIME_Message->get_all_parts();                                                                
            $count  = 0;   
            $this->Yenc   = false;                                       
            foreach ($parts as $part)                                              
            {              
                $subject = isset($part["header"]["subject"]) ? $part["header"]["subject"] : "";    
                if (isset($part['header']['content-transfer-encoding']) && 
                    strlen($part['header']['content-transfer-encoding']) > 0)
                {
                    $this->Encoding = $part['header']['content-transfer-encoding'];  
                }                                              
                $body    = $part["body"];                                              
                if ( (strpos($body, "ybegin") !== false) || (strpos(strtolower($subject), "yenc") !== false) )                                             
                { // YENC decoding  
                    $arr = array ();                                             
                    $arr["header"]     = array ("content-type"=>"image/jpeg", "content-transfer-encoding" => "yenc");                                             
                    $arr["body"]       = $part["body"];   
                    $this->Yenc      = true;                            
                }                                               
                $attachment_id = $count;                                           
                $count++;                                              
            }                                               

                                                        
            if ($MIME_Message->get_total_part() > $attachment_id)                                              
            {                                             
                $header = $MIME_Message->get_part_header($attachment_id);                                             
                $body   = $MIME_Message->get_part_body($attachment_id);                                             
                if (strcmp($header["content-type"],"") == 0)                                              
                {                                             
                    header("Content-Type: text/html");                                             
                    echo $messages_ini["error"]["request_fail"];                                             
                }                                              
                else                                              
                {                          
                    $content[] = $MIME_Message->get_part($attachment_id);
                }                                             
            }                                              
            else                                              
            {                                             
                header("Content-Type: text/html");                                             
                echo $messages_ini["error"]["multipart_fail"];                                             
            }  
        }    
        return $content;
    }

 }
